<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备名称" prop="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="品牌" prop="brand">
        <el-input
          v-model="queryParams.brand"
          placeholder="请输入品牌"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择设备状态" clearable>
          <el-option
            v-for="dict in dict.type.rental_device_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:devices:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:devices:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:devices:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:devices:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 批量操作工具栏 -->
    <div v-if="selectedDevices.length > 0" class="batch-toolbar">
      <el-alert
        :title="`已选择 ${selectedDevices.length} 个设备`"
        type="info"
        show-icon
        :closable="false"
      >
        <template slot="default">
          <div class="batch-actions">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:devices:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-goods"
              @click="handleInventoryDetail(scope.row)"
              style="color: #67c23a;"
            >库存详情</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:devices:remove']"
            >删除</el-button>
            <el-button size="small" @click="clearSelection">取消选择</el-button>
          </div>
        </template>
      </el-alert>
    </div>

    <!-- 卡片网格布局 -->
    <div v-loading="loading" class="devices-grid">
      <div 
        v-for="device in devicesList" 
        :key="device.deviceId" 
        class="device-card"
      >

        <!-- 设备图片 -->
        <div class="device-image">
          <el-image
            v-if="device.images"
            :src="JSON.parse(device.images)[0]"
            :preview-src-list="JSON.parse(device.images)"
            fit="cover"
            class="image"
          >
            <div slot="error" class="image-placeholder">
              <div class="default-icon-wrapper">
                <i class="el-icon-picture-outline"></i>
                <span class="device-type-text">设备图片</span>
              </div>
            </div>
          </el-image>
          <div v-else class="image-placeholder">
            <div class="default-icon-wrapper">
              <i class="el-icon-picture-outline"></i>
              <span class="device-type-text">设备图片</span>
            </div>
          </div>
        </div>

        <!-- 设备信息 -->
        <div class="device-info">
          <div class="device-header">
            <h3 class="device-name" :title="device.deviceName">{{ device.deviceName }}</h3>
            <div class="device-status">
              <dict-tag :options="dict.type.rental_device_status" :value="device.status"/>
            </div>
          </div>

          <!-- 重要信息显示 -->
          <div class="key-info">
            <div class="key-info-row">
              <div class="rent-period">
                <i class="el-icon-time"></i>
                <span class="label">租期:</span>
                <span class="value highlight">{{ device.minRentDays || 1 }}-{{ device.maxRentDays || 30 }}天</span>
              </div>
              <div class="purchase-date">
                <i class="el-icon-date"></i>
                <span class="label">购于:</span>
                <span class="value">{{ parseTime(device.purchaseDate, '{y}-{m}-{d}') || '-' }}</span>
              </div>
            </div>
            <div class="key-info-row">
              <div class="purchase-price">
                <i class="el-icon-money"></i>
                <span class="label">一口价:</span>
                <span class="value price-highlight">￥{{ device.purchasePrice || 0 }}</span>
              </div>
              <div class="daily-rent">
                <i class="el-icon-coin"></i>
                <span class="label">日租:</span>
                <span class="value price">￥{{ device.dailyRent || 0 }}/天</span>
              </div>
            </div>
          </div>

          <div class="device-details">
            <div class="detail-row">
              <span class="label">编码:</span>
              <span class="value">{{ device.deviceCode }}</span>
            </div>
            <div class="detail-row">
              <span class="label">分类:</span>
              <span class="value">{{ getCategoryName(device.categoryId) }}</span>
            </div>
            <div class="detail-row">
              <span class="label">品牌:</span>
              <span class="value">{{ device.brand || '-' }}</span>
            </div>
            <div class="detail-row">
              <span class="label">型号:</span>
              <span class="value">{{ device.model || '-' }}</span>
            </div>
            <div class="detail-row">
              <span class="label">押金:</span>
              <span class="value price">￥{{ device.deposit || 0 }}</span>
            </div>
            <div class="detail-row">
              <span class="label">位置:</span>
              <span class="value location">{{ getLocationText(device) }}</span>
            </div>
          </div>

          <!-- 库存信息 -->
          <div class="inventory-info" v-if="device.inventory">
            <div class="inventory-row">
              <span class="inventory-label">库存状态:</span>
              <div class="inventory-details">
                <span class="inventory-item available">
                  <i class="el-icon-check"></i>
                  可用: {{ device.inventory.availableQuantity || 0 }}
                </span>
                <span class="inventory-item rented">
                  <i class="el-icon-time"></i>
                  已租: {{ device.inventory.rentedQuantity || 0 }}
                </span>
                <span class="inventory-item total">
                  <i class="el-icon-goods"></i>
                  总数: {{ device.inventory.totalQuantity || 0 }}
                </span>
              </div>
            </div>
            <div class="inventory-row" v-if="(device.inventory.maintenanceQuantity || 0) > 0 || (device.inventory.damagedQuantity || 0) > 0">
              <span class="inventory-label">异常状态:</span>
              <div class="inventory-details">
                <span v-if="(device.inventory.maintenanceQuantity || 0) > 0" class="inventory-item maintenance">
                  <i class="el-icon-setting"></i>
                  维修: {{ device.inventory.maintenanceQuantity }}
                </span>
                <span v-if="(device.inventory.damagedQuantity || 0) > 0" class="inventory-item damaged">
                  <i class="el-icon-warning"></i>
                  损坏: {{ device.inventory.damagedQuantity }}
                </span>
              </div>
            </div>
          </div>
          <div class="inventory-info" v-else>
            <div class="inventory-row">
              <span class="inventory-label">库存状态:</span>
              <span class="inventory-item no-data">
                <i class="el-icon-info"></i>
                暂无库存数据
              </span>
            </div>
          </div>

          <div class="device-description" v-if="device.description">
            <p :title="device.description">{{ device.description }}</p>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="device-actions">
          <el-button
            size="small"
            type="primary"
            icon="el-icon-edit"
            @click.stop="handleUpdate(device)"
            v-hasPermi="['system:devices:edit']"
          >编辑</el-button>
          <el-button
            size="small"
            type="success"
            icon="el-icon-goods"
            @click.stop="handleInventoryDetail(device)"
          >库存详情</el-button>
          <el-button
            size="small"
            type="danger"
            icon="el-icon-delete"
            @click.stop="handleDelete(device)"
            v-hasPermi="['system:devices:remove']"
          >删除</el-button>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && devicesList.length === 0" class="empty-state">
        <el-empty description="暂无设备数据">
          <el-button 
            type="primary" 
            @click="handleAdd"
            v-hasPermi="['system:devices:add']"
          >添加设备</el-button>
        </el-empty>
      </div>
    </div>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 库存详情弹窗 -->
    <InventoryDetailDialog 
      :visible.sync="inventoryDialogVisible"
      :device-info="selectedDevice"
      @refresh="getList"
      @close="handleInventoryDialogClose"
    />

    <!-- 添加或修改设备对话框 -->
    <el-dialog 
      :title="title" 
      :visible.sync="open" 
      width="80%" 
      top="5vh" 
      :modal="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
      class="device-dialog"
    >
      <template #title>
        <div class="dialog-header">
          <span class="dialog-title">{{ title }}</span>
          <el-button 
            type="text" 
            class="close-btn" 
            @click="cancel"
            icon="el-icon-close"
          ></el-button>
        </div>
      </template>
      <div class="dialog-content">
        <!-- 设备图片展示区域 -->
        <div class="device-images-section">
          <h3 class="section-title">设备图片</h3>
          <div class="images-container">
            <!-- 图片列表 -->
            <div class="image-gallery">
              <!-- 已上传的图片 -->
              <div 
                v-for="(image, index) in getImageList(form.images)"
                :key="'existing-' + index"
                class="image-item"
              >
                <el-image
                  :src="image"
                  :preview-src-list="getImageList(form.images)"
                  fit="cover"
                  class="preview-image"
                >
                  <div slot="error" class="image-error">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
                <!-- 删除按钮 -->
                <div class="image-delete-btn" @click="removeImage(index)">
                  <i class="el-icon-close"></i>
                </div>
              </div>
              
              <!-- 上传按钮 -->
              <div class="upload-item">
                <el-upload
                  class="image-uploader"
                  action="#"
                  :http-request="uploadImage"
                  :show-file-list="false"
                  :before-upload="beforeImageUpload"
                  accept="image/*"
                >
                  <div class="upload-placeholder">
                    <i class="el-icon-plus"></i>
                    <div class="upload-text">上传图片</div>
                  </div>
                </el-upload>
              </div>
            </div>
          </div>
        </div>

        <!-- 设备信息表单 -->
        <div class="device-form-section">
          <h3 class="section-title">设备信息</h3>
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备编码" prop="deviceCode">
              <el-input v-model="form.deviceCode" placeholder="请输入设备编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备分类" prop="categoryId">
              <el-cascader
                v-model="form.categoryPath"
                :options="categoryOptions"
                :props="cascaderProps"
                placeholder="请选择设备分类"
                clearable
                filterable
                @change="handleCategoryChange"
                style="width: 100%"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="form.brand" placeholder="请输入品牌" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="型号" prop="model">
              <el-input v-model="form.model" placeholder="请输入型号" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="规格参数" prop="specifications">
              <el-input v-model="form.specifications" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="设备描述" prop="description">
              <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>


          <el-col :span="12">
            <el-form-item label="日租金" prop="dailyRent">
              <el-input v-model="form.dailyRent" placeholder="请输入日租金" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="押金" prop="deposit">
              <el-input v-model="form.deposit" placeholder="请输入押金" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最少租赁天数" prop="minRentDays">
              <el-input v-model="form.minRentDays" placeholder="请输入最少租赁天数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最多租赁天数" prop="maxRentDays">
              <el-input v-model="form.maxRentDays" placeholder="请输入最多租赁天数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.rental_device_status"
                  :key="dict.value"
:label="parseInt(dict.value)"                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备所在省份" prop="locationProvince">
              <el-input v-model="form.locationProvince" placeholder="请输入设备所在省份" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备所在城市" prop="locationCity">
              <el-input v-model="form.locationCity" placeholder="请输入设备所在城市" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备所在区县" prop="locationDistrict">
              <el-input v-model="form.locationDistrict" placeholder="请输入设备所在区县" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备详细地址" prop="locationAddress">
              <el-input v-model="form.locationAddress" placeholder="请输入设备详细地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="购买日期" prop="purchaseDate">
              <el-date-picker clearable style="width: 100%"
                v-model="form.purchaseDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择购买日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="购买价格" prop="purchasePrice">
              <el-input v-model="form.purchasePrice" placeholder="请输入购买价格" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间" prop="createdTime">
              <el-date-picker clearable style="width: 100%"
                v-model="form.createdTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择创建时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="更新时间" prop="updatedTime">
              <el-date-picker clearable style="width: 100%"
                v-model="form.updatedTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择更新时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
            </el-row>
          </el-form>
        </div>


      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" size="medium">确 定</el-button>
        <el-button @click="cancel" size="medium">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDevices, listDevicesWithInventory, getDevices, delDevices, addDevices, updateDevices, uploadDeviceImage } from "@/api/system/devices";
import { listCategories } from "@/api/system/categories";
import categoryStorage from "@/utils/categoryStorage";
import InventoryDetailDialog from "./components/InventoryDetailDialog.vue";

export default {
  name: "Devices",
  components: {
    InventoryDetailDialog
  },
  dicts: ['rental_device_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 卡片模式下选中的设备
      selectedDevices: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备表格数据
      devicesList: [],
      // 分类级联选择器数据
      categoryOptions: [],
      // 级联选择器配置
      cascaderProps: {
        value: 'categoryId',
        label: 'categoryName',
        children: 'children',
        checkStrictly: true, // 可以选择任意一级
        emitPath: true // 返回完整路径数组，用于级联选择器显示
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceCode: null,
        deviceName: null,
        categoryId: null,
        brand: null,
        model: null,
        specifications: null,
        description: null,
        images: null,

        dailyRent: null,
        deposit: null,
        minRentDays: null,
        maxRentDays: null,
        status: null,
        locationProvince: null,
        locationCity: null,
        locationDistrict: null,
        locationAddress: null,
        purchaseDate: null,
        purchasePrice: null,
        createdTime: null,
        updatedTime: null
      },
      // 表单参数
      form: {},
      // 库存详情弹窗相关
      inventoryDialogVisible: false,
      selectedDevice: {},

      // 表单校验
      rules: {
        deviceCode: [
          { required: true, message: "设备编码不能为空", trigger: "blur" }
        ],
        deviceName: [
          { required: true, message: "设备名称不能为空", trigger: "blur" }
        ],
        categoryId: [
          { required: true, message: "分类ID不能为空", trigger: "blur" }
        ],

        dailyRent: [
          { required: true, message: "日租金不能为空", trigger: "blur" }
        ],
        deposit: [
          { required: true, message: "押金不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "设备状态：0-下架，1-可租，2-已租出，3-维修中，4-损坏不能为空", trigger: "change" }
        ],
        createdTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        updatedTime: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ]
      }
    };
  },

  created() {
    // 先初始化分类数据，再加载设备列表
    this.initCategoryData().then(() => {
      this.getList();
    }).catch(() => {
      // 即使分类数据加载失败，也要加载设备列表
      this.getList();
    });
  },
  methods: {
    /** 查询设备列表 */
    getList() {
      this.loading = true;
      // 使用优化后的接口，直接获取设备+库存信息
      listDevicesWithInventory(this.queryParams).then(response => {
        this.devicesList = response.rows;
        this.total = response.total;
        this.loading = false;
        
        console.log('获取设备+库存数据成功:', response.rows.length, '条记录');
      }).catch(error => {
        console.error('获取设备列表失败:', error);
        this.loading = false;
      });
    },
    
    /** 初始化分类数据 */
    initCategoryData() {
      return new Promise((resolve, reject) => {
        // 优先从localStorage获取分类数据
        if (categoryStorage.hasCategoriesData()) {
          this.categoryOptions = categoryStorage.getCategoriesData();
          console.log('从localStorage加载分类数据', this.categoryOptions.length, '条记录');
          resolve(this.categoryOptions);
        } else {
          // 如果localStorage中没有数据，则初始化
          console.log('开始初始化分类数据到localStorage...');
          initCategoriesStorage().then(categories => {
            this.categoryOptions = categories;
            console.log('初始化分类数据到localStorage完成', categories.length, '条记录');
            resolve(categories);
          }).catch(error => {
            console.error('初始化分类数据失败:', error);
            this.categoryOptions = [];
            reject(error);
          });
        }
      });
    },
    
    /** 获取分类列表（备用方法） */
    getCategoryList() {
      listCategories().then(response => {
        console.log('备用方法获取分类API响应:', response);
        // 根据API文档，分类数据在rows中
        this.categoryOptions = response.rows || response.data || [];
        console.log('备用方法获取分类数据:', this.categoryOptions.length, '条记录');
      }).catch(error => {
        console.error('获取分类列表失败:', error);
        this.categoryOptions = [];
      });
    },
    
    /** 处理分类选择变化 */
    handleCategoryChange(value) {
      console.log('级联选择器值变化:', value);
      // 级联选择器返回的是路径数组，取最后一个值作为categoryId
      if (Array.isArray(value) && value.length > 0) {
        this.form.categoryId = value[value.length - 1];
      } else {
        this.form.categoryId = null;
      }
      console.log('设置分类ID:', this.form.categoryId);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deviceId: null,
        deviceCode: null,
        deviceName: null,
        categoryId: null,
        categoryPath: [],
        brand: null,
        model: null,
        specifications: null,
        description: null,
        images: null,

        dailyRent: null,
        deposit: null,
        minRentDays: null,
        maxRentDays: null,
        status: null,
        locationProvince: null,
        locationCity: null,
        locationDistrict: null,
        locationAddress: null,
        purchaseDate: null,
        purchasePrice: null,
        createdTime: null,
        updatedTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.deviceId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    /** 处理库存详情按钮点击 */
    handleInventoryDetail(device) {
      this.selectedDevice = device;
      this.inventoryDialogVisible = true;
    },

    /** 库存详情弹窗关闭处理 */
    handleInventoryDialogClose() {
      this.selectedDevice = {};
      this.inventoryDialogVisible = false;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const deviceId = row.deviceId || this.ids
      getDevices(deviceId).then(response => {
        this.form = response.data;
        console.log('编辑设备数据:', this.form);
        
        // 设置级联选择器的值 - 需要构建完整的分类路径
        if (this.form.categoryId) {
          const categoryPath = this.buildCategoryPath(this.form.categoryId);
          this.form.categoryPath = categoryPath;
          console.log('设置级联选择器路径:', categoryPath);
        } else {
          this.form.categoryPath = [];
        }
        

        
        this.open = true;
        this.title = "修改设备";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.deviceId != null) {
            // 修改操作
            updateDevices(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // 新增操作
            addDevices(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const deviceIds = row.deviceId || this.ids;
      this.$modal.confirm('是否确认删除设备编号为"' + deviceIds + '"的数据项？').then(function() {
        return delDevices(deviceIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/devices/export', {
        ...this.queryParams
      }, `devices_${new Date().getTime()}.xlsx`)
    },
    
    // === 卡片布局相关方法 ===
    
    /** 点击设备卡片 */
    handleCardClick(device) {
      this.handleUpdate(device);
    },
    
    /** 获取图片列表 */
    getImageList(imagesStr) {
      if (!imagesStr) return [];
      try {
        const images = JSON.parse(imagesStr);
        return Array.isArray(images) ? images : [];
      } catch (e) {
        return [];
      }
    },
    
    /** 检查设备是否被选中 */
    isSelected(device) {
      return this.selectedDevices.some(item => item.deviceId === device.deviceId);
    },
    
    /** 切换设备选择状态 */
    toggleSelection(device) {
      const index = this.selectedDevices.findIndex(item => item.deviceId === device.deviceId);
      if (index > -1) {
        this.selectedDevices.splice(index, 1);
      } else {
        this.selectedDevices.push(device);
      }
      // 同步更新ids数组以保持兼容性
      this.ids = this.selectedDevices.map(item => item.deviceId);
      this.single = this.selectedDevices.length !== 1;
      this.multiple = this.selectedDevices.length === 0;
    },
    
    /** 清除所有选择 */
    clearSelection() {
      this.selectedDevices = [];
      this.ids = [];
      this.single = true;
      this.multiple = true;
    },
    


    /** 批量删除设备 */
    handleBatchDelete() {
      if (this.selectedDevices.length === 0) {
        this.$modal.msgWarning('请先选择要删除的设备');
        return;
      }
      
      const deviceIds = this.selectedDevices.map(item => item.deviceId);
      const deviceNames = this.selectedDevices.map(item => item.deviceName).join('、');
      
      this.$modal.confirm(`是否确认删除设备"${deviceNames}"？`).then(() => {
        return delDevices(deviceIds);
      }).then(() => {
        this.getList();
        this.clearSelection();
        this.$modal.msgSuccess('删除成功');
      }).catch(() => {});
    },
    
    /** 批量导出设备 */
    handleBatchExport() {
      if (this.selectedDevices.length === 0) {
        this.$modal.msgWarning('请先选择要导出的设备');
        return;
      }
      
      const deviceIds = this.selectedDevices.map(item => item.deviceId);
      this.download('system/devices/export', {
        deviceIds: deviceIds.join(',')
      }, `selected_devices_${new Date().getTime()}.xlsx`);
    },
    
    /** 获取位置文本 */
    getLocationText(device) {
      const parts = [];
      if (device.locationProvince) parts.push(device.locationProvince);
      if (device.locationCity) parts.push(device.locationCity);
      if (device.locationDistrict) parts.push(device.locationDistrict);
      return parts.length > 0 ? parts.join(' ') : '-';
    },
    
    /** 从localStorage获取分类名称 */
    getCategoryName(categoryId) {
      return categoryStorage.getCategoryName(categoryId);
    },
    
    /** 从localStorage获取分类完整路径 */
    getCategoryPath(categoryId) {
      return categoryStorage.getCategoryPath(categoryId);
    },
    
    /** 构建级联选择器需要的分类路径数组 */
    buildCategoryPath(categoryId) {
      if (!categoryId) return [];
      
      // 递归查找分类路径
      const findPath = (categories, targetId, currentPath = []) => {
        if (!Array.isArray(categories)) return null;
        
        for (const category of categories) {
          const newPath = [...currentPath, category.categoryId];
          
          if (category.categoryId == targetId) {
            return newPath;
          }
          
          if (category.children && category.children.length > 0) {
            const result = findPath(category.children, targetId, newPath);
            if (result) {
              return result;
            }
          }
        }
        
        return null;
      };
      
      const path = findPath(this.categoryOptions, categoryId);
      console.log(`构建分类ID ${categoryId} 的路径:`, path);
      return path || [];
    },
    
    // === 设备图片管理相关方法 ===
    
    /** 获取图片列表 */
    getImageList(imagesStr) {
      // 处理空值情况
      if (!imagesStr || imagesStr === 'null' || imagesStr === 'undefined') {
        return [];
      }
      
      try {
        const images = JSON.parse(imagesStr);
        return Array.isArray(images) ? images : [];
      } catch (e) {
        console.warn('解析图片列表失败:', e, '原始数据:', imagesStr);
        return [];
      }
    },
    
    /** 上传图片前的校验 */
    beforeImageUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt10M = file.size / 1024 / 1024 < 10;
      
      if (!isImage) {
        this.$modal.msgError('上传文件只能是图片格式!');
        return false;
      }
      if (!isLt10M) {
        this.$modal.msgError('上传图片大小不能超过10MB!');
        return false;
      }
      return true;
    },
    
    /** 上传图片 */
    uploadImage(options) {
      const formData = new FormData();
      formData.append('file', options.file);
      
      this.$modal.loading('正在上传图片...');
      
      uploadDeviceImage(formData).then(response => {
        this.$modal.closeLoading();
        
        if (response.code === 200) {
          // 获取上传后的图片URL（根据API文档，data直接是URL字符串）
          const imageUrl = response.data;
          
          // 将新图片添加到设备图片列表中
          let currentImages = [];
          if (this.form.images) {
            try {
              currentImages = JSON.parse(this.form.images);
            } catch (e) {
              currentImages = [];
            }
          }
          
          currentImages.push(imageUrl);
          this.form.images = JSON.stringify(currentImages);
          
          this.$modal.msgSuccess('图片上传成功!');
          console.log('图片上传成功:', imageUrl);
        } else {
          this.$modal.msgError('图片上传失败: ' + (response.msg || '未知错误'));
        }
      }).catch(error => {
        this.$modal.closeLoading();
        console.error('图片上传失败:', error);
        this.$modal.msgError('图片上传失败，请稍后重试');
      });
    },
    
    /** 删除图片 */
    removeImage(index) {
      this.$modal.confirm('确定要删除这张图片吗？').then(() => {
        let currentImages = [];
        if (this.form.images) {
          try {
            currentImages = JSON.parse(this.form.images);
          } catch (e) {
            currentImages = [];
          }
        }
        
        // 删除指定索引的图片
        currentImages.splice(index, 1);
        
        // 更新表单数据（始终保持JSON字符串格式，空数组时为"[]"）
        this.form.images = JSON.stringify(currentImages);
        
        this.$modal.msgSuccess('图片删除成功!');
        console.log('删除图片后的图片列表:', this.form.images);
      }).catch(() => {
        // 用户取消删除
      });
    }
  }
};
</script>

<style lang="scss" scoped>
/* 批量操作工具栏样式 */
.batch-toolbar {
  margin-bottom: 16px;
  
  .batch-actions {
    margin-top: 8px;
    
    .el-button {
      margin-right: 8px;
    }
  }
}

/* 卡片网格布局 */
.devices-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
  gap: 20px;
  padding: 0;
}

/* 设备卡片样式 */
.device-card {
  position: relative;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
  overflow: hidden;
  border: 2px solid transparent;
  
  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  }
  
  &.selected {
    border-color: #409eff;
    box-shadow: 0 4px 20px rgba(64, 158, 255, 0.3);
  }
}

/* 选择框样式 */
.card-checkbox {
  position: absolute;
  top: 12px;
  left: 12px;
  z-index: 10;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  padding: 4px;
  backdrop-filter: blur(4px);
}

/* 设备图片样式 */
.device-image {
  width: 100%;
  height: 200px;
  position: relative;
  overflow: hidden;
  
  .image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  
  .image-placeholder {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    position: relative;
    
    .default-icon-wrapper {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      text-align: center;
      
      i {
        font-size: 120px;
        margin-bottom: 16px;
        opacity: 0.9;
        line-height: 1;
      }
      
      .device-type-text {
        font-size: 14px;
        font-weight: 600;
        opacity: 0.9;
        letter-spacing: 0.5px;
        text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
      }
    }
  }
}

/* 设备信息区域 */
.device-info {
  padding: 16px;
}

/* 设备头部信息 */
.device-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
  
  .device-name {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
    margin: 0;
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin-right: 8px;
  }
  
  .device-status {
    flex-shrink: 0;
  }
}

/* 设备详情列表 */
.device-details {
  margin-bottom: 12px;
  
  .detail-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 4px 0;
    border-bottom: 1px solid #f5f5f5;
    
    &:last-child {
      border-bottom: none;
    }
    
    .label {
      font-size: 13px;
      color: #909399;
      font-weight: 500;
      min-width: 60px;
    }
    
    .value {
      font-size: 14px;
      color: #606266;
      text-align: right;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      max-width: 200px;
      
      &.price {
        color: #f56c6c;
        font-weight: 600;
      }
      
      &.location {
        color: #67c23a;
      }
    }
  }
}

/* 设备描述 */
.device-description {
  margin-top: 12px;
  
  p {
    color: #666;
    font-size: 13px;
    line-height: 1.4;
    margin: 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

/* 库存信息样式 */
.inventory-info {
  margin-top: 12px;
  padding: 8px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 3px solid #409eff;
  
  .inventory-row {
    display: flex;
    align-items: flex-start;
    margin-bottom: 6px;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .inventory-label {
    font-size: 12px;
    color: #666;
    font-weight: 500;
    min-width: 60px;
    margin-right: 8px;
    line-height: 20px;
  }
  
  .inventory-details {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
  }
  
  .inventory-item {
    display: inline-flex;
    align-items: center;
    font-size: 11px;
    padding: 2px 6px;
    border-radius: 10px;
    font-weight: 500;
    
    i {
      margin-right: 2px;
      font-size: 10px;
    }
    
    &.available {
      background: #e8f5e8;
      color: #52c41a;
      border: 1px solid #b7eb8f;
    }
    
    &.rented {
      background: #fff7e6;
      color: #fa8c16;
      border: 1px solid #ffd591;
    }
    
    &.total {
      background: #e6f7ff;
      color: #1890ff;
      border: 1px solid #91d5ff;
    }
    
    &.maintenance {
      background: #f6ffed;
      color: #722ed1;
      border: 1px solid #d3adf7;
    }
    
    &.damaged {
      background: #fff2f0;
      color: #f5222d;
      border: 1px solid #ffadd2;
    }
    
    &.no-data {
      background: #f5f5f5;
      color: #999;
      border: 1px solid #d9d9d9;
    }
  }
}

/* 关键信息区域 */
.key-info {
  margin-bottom: 16px;
  padding: 12px;
  background: linear-gradient(135deg, #e3f2fd 0%, #f3e5f5 100%);
  border-radius: 8px;
  color: #333;
  border: 1px solid #e1e8ed;
  
  .key-info-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    &:not(:last-child) {
      margin-bottom: 8px;
    }
    
    > div {
      display: flex;
      align-items: center;
      gap: 4px;
      
      i {
        font-size: 14px;
        opacity: 0.7;
        color: #666;
      }
      
      .label {
        font-size: 12px;
        opacity: 0.8;
        margin-right: 4px;
        color: #666;
      }
      
      .value {
        font-size: 13px;
        font-weight: 500;
        color: #333;
        
        &.highlight {
          font-weight: 600;
          color: #1976d2;
        }
        
        &.price {
          color: #ff9800;
          font-weight: 600;
        }
        
        &.price-highlight {
          color: #e91e63;
          font-weight: 700;
          font-size: 14px;
        }
      }
    }
  }
}

/* 操作按钮区域 */
.device-actions {
  padding: 0 16px 16px;
  display: flex;
  gap: 8px;
  
  .el-button {
    flex: 1;
    border-radius: 8px;
    font-weight: 500;
  }
}

/* 空状态样式 */
.empty-state {
  grid-column: 1 / -1;
  padding: 60px 20px;
  text-align: center;
  
  .el-empty {
    padding: 40px 0;
  }
}



/* 响应式设计 */
@media (max-width: 1200px) {
  .devices-grid {
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 16px;
  }
}

@media (max-width: 768px) {
  .devices-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }
  
  .device-card {
    margin: 0 8px;
  }
  
  .device-info {
    padding: 12px;
  }
  
  .device-header .device-name {
    font-size: 16px;
  }
}

/* 加载状态优化 */
.devices-grid[v-loading] {
  min-height: 400px;
}

/* 80%宽度弹窗样式 */
.device-dialog {
  .el-dialog {
    margin: 5vh auto;
    height: 90vh;
    max-height: 90vh;
    border-radius: 8px;
    overflow: hidden;
  }
  
  .el-dialog__header {
    padding: 0;
    margin: 0;
    border-bottom: 1px solid #ebeef5;
  }
  
  .dialog-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 24px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    
    .dialog-title {
      font-size: 20px;
      font-weight: 600;
      margin: 0;
    }
    
    .close-btn {
      color: white;
      font-size: 24px;
      padding: 8px;
      border-radius: 50%;
      background: rgba(255, 255, 255, 0.1);
      border: none;
      transition: all 0.3s ease;
      
      &:hover {
        background: rgba(255, 255, 255, 0.2);
        transform: scale(1.1);
      }
      
      i {
        font-size: 20px;
      }
    }
  }
  
  .el-dialog__body {
    padding: 0;
    height: calc(90vh - 140px);
    overflow-y: auto;
  }
  
  .dialog-content {
    display: flex;
    height: 100%;
    
    .device-images-section {
      flex: 0 0 400px;
      padding: 24px;
      background: #f8f9fa;
      border-right: 1px solid #ebeef5;
      
      .section-title {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
        margin: 0 0 16px 0;
        padding-bottom: 8px;
        border-bottom: 2px solid #409eff;
      }
      
      .images-container {
        .image-gallery {
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
          gap: 12px;
          
          .image-item {
            position: relative;
            
            .preview-image {
              width: 100%;
              height: 150px;
              border-radius: 8px;
              overflow: hidden;
              border: 2px solid #ebeef5;
              transition: all 0.3s ease;
              
              &:hover {
                border-color: #409eff;
                transform: scale(1.02);
              }
            }
            
            .image-delete-btn {
              position: absolute;
              top: 8px;
              right: 8px;
              width: 24px;
              height: 24px;
              background: rgba(255, 255, 255, 0.9);
              border-radius: 50%;
              display: flex;
              align-items: center;
              justify-content: center;
              cursor: pointer;
              transition: all 0.3s ease;
              box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
              
              &:hover {
                background: #f56c6c;
                color: white;
                transform: scale(1.1);
              }
              
              i {
                font-size: 14px;
                font-weight: bold;
              }
            }
          }
          
          .upload-item {
            .image-uploader {
              width: 150px;
              height: 150px;
              
              .upload-placeholder {
                width: 150px;
                height: 150px;
                border: 2px dashed #d9d9d9;
                border-radius: 8px;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                cursor: pointer;
                transition: all 0.3s ease;
                background: #fafafa;
                
                &:hover {
                  border-color: #409eff;
                  background: #f0f9ff;
                  transform: scale(1.02);
                }
                
                i {
                  font-size: 36px;
                  color: #c0c4cc;
                  margin-bottom: 8px;
                  transition: all 0.3s ease;
                }
                
                .upload-text {
                  font-size: 13px;
                  color: #606266;
                  font-weight: 500;
                  text-align: center;
                  line-height: 1.2;
                }
                
                &:hover i {
                  color: #409eff;
                }
                
                &:hover .upload-text {
                  color: #409eff;
                }
              }
            }
          }
          
          .image-error {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100%;
            width: 100%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            
            i {
              font-size: 60px;
              opacity: 0.9;
            }
          }
        }
        
        .no-images {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          height: 300px;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          border: 2px dashed rgba(255, 255, 255, 0.3);
          border-radius: 12px;
          color: white;
          transition: all 0.3s ease;
          
          &:hover {
            transform: scale(1.02);
            border-color: rgba(255, 255, 255, 0.5);
          }
          
          i {
            font-size: 80px;
            margin-bottom: 16px;
            opacity: 0.9;
          }
          
          span {
            font-size: 16px;
            font-weight: 500;
            opacity: 0.9;
          }
        }
      }
    }
    
    .device-form-section {
      flex: 1;
      padding: 24px;
      
      .section-title {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
        margin: 0 0 20px 0;
        padding-bottom: 8px;
        border-bottom: 2px solid #67c23a;
      }
      
      .el-form {
        .el-form-item {
          margin-bottom: 18px;
          
          .el-form-item__label {
            font-weight: 500;
            color: #606266;
          }
        }
      }
    }
  }
  
  .el-dialog__footer {
    padding: 20px 24px;
    background: #f8f9fa;
    border-top: 1px solid #ebeef5;
    text-align: right;
    
    .el-button {
      padding: 10px 20px;
      font-weight: 500;
    }
  }
}

/* 字典标签样式优化 */
:deep(.el-tag) {
  border-radius: 12px;
  font-size: 11px;
  padding: 2px 8px;
  font-weight: 500;
}

/* 分页样式调整 */
.pagination {
  margin-top: 24px;
  text-align: center;
}
</style>
